package com.ycy;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.DefaultFastFileStorageClient;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

import static javafx.scene.input.KeyCode.F;
import static jdk.nashorn.internal.runtime.regexp.joni.encoding.CharacterType.ASCII;

@Slf4j
public class FdfsDemo {

  FastFileStorageClient storageClient;

  public static void main(String[] args) {
    FastFileStorageClient storageClient;
    storageClient = new DefaultFastFileStorageClient();

//    storageClient.uploadFile( )
//    System.out.println("ClientGlobal.configInfo(): " + ClientGlobal.configInfo());

  }


  /**
   * 上传图片
   */
  public String uploadImage(byte[] imageByte, String fileExtension, boolean withThumbnail) throws IOException {
    StorePath storePath;
    try (InputStream inputStream = new ByteArrayInputStream(imageByte)) {
      if (withThumbnail) {
        storePath = storageClient.uploadImageAndCrtThumbImage(inputStream, imageByte.length,
                fileExtension, null);
      } else {
        storePath = storageClient.uploadFile(inputStream, imageByte.length,
                fileExtension, null);
      }
    }
    String resAccessUrl = getResAccessUrl(storePath);
    log.info("图片上传成功: {}", resAccessUrl);
    return resAccessUrl;
  }

  /**
   * 上传文件
   *
   * @param file 文件对象
   * @return 文件访问地址
   * @throws IOException 异常
   */
  public String uploadFile(File file) throws IOException {
    StorePath storePath;
    try (FileInputStream inputStream = new FileInputStream(file)) {
      storePath = storageClient.uploadFile(inputStream, file.length(),
              FilenameUtils.getExtension(file.getName()), null);
    }
    return getResAccessUrl(storePath);
  }

  public String uploadFile(ByteArrayOutputStream byteArrayOutputStream, String fileExtension) throws IOException {
    StorePath storePath;
    byte[] bytes = byteArrayOutputStream.toByteArray();
    try (InputStream inputStream = new ByteArrayInputStream(bytes)) {
      storePath = storageClient.uploadFile(inputStream, bytes.length, fileExtension, null);
    }
    return getResAccessUrl(storePath);
  }

  /**
   * 封装图片完整URL地址
   *
   * @param storePath 存储路径
   * @return String
   */
  private String getResAccessUrl(StorePath storePath) {
    return storePath.getFullPath();
  }

}
